<template>
  <div class="mian-container">
    <div class="search">
      <el-input
        v-model="roleName"
        placeholder="请输入角色名称查询"
        style="width: 200px"
        size="small"
      ></el-input>
      <el-button
        type="info"
        plain
        style="margin-left: 10px"
        size="small"
        @click="search"
        >查询</el-button
      >
      <el-button
        type="warning"
        plain
        style="margin-left: 10px"
        size="small"
        @click="reset"
        >重置</el-button
      >
    </div>

    <div class="operation">
      <el-button type="primary" plain size="small" @click="handleAdd"
        >新增</el-button
      >
    </div>

    <div class="table">
      <el-table :data="tableData" stripe>
        <el-table-column prop="roleName" label="角色" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="description"
          label="角色描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template v-slot="scope">
            <el-button
              plain
              type="primary"
              size="mini"
              :disabled="scope.row.roleName == '超级管理员'"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              plain
              type="danger"
              size="mini"
              :disabled="scope.row.roleName == '超级管理员'"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          :total="total"
          layout="total,prev,pager,next"
        >
        </el-pagination>
      </div>
    </div>

    <div id="editDialog">
      <el-dialog
        title="用户管理"
        :visible.sync="showVisiable"
        width="50%"
        :close-on-click-modal="false"
        destory-on-close
      >
        <el-form
          label-width="100px"
          :model="editForm"
          ref="formRef"
          :rules="rules"
        >
          <el-form-item prop="roleName" label="角色名称">
            <el-input
              v-model="editForm.roleName"
              auto-complete="off"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input
              v-model="editForm.description"
              type="textarea"
              auto-complete="off"
              size="small"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item prop="power" label="角色权限">
            <el-tree
              style="margin: 10px 0"
              ref="tree"
              :data="roleData"
              node-key="id"
              show-checkbox
              @check-change="handleCheckChange"
              default-expand-all
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancle">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  reqRoleList,
  reqMenuList,
  addRole,
  updateRole,
  delRole,
  searchRole,
} from "@/api/role";
export default {
  name: "role",
  data() {
    return {
      tableData: [],
      roleData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      roleName: "",
      delBatchData: [],
      showVisiable: false,
      dialogVisible: false,
      editForm: {
        roleName: "",
        description: "",
        routes: [],
        power: [],
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
        power: [{ required: true, message: "请选择角色权限", trigger: "blur" }],
      },
    };
  },
  methods: {
    cancle() {
      this.$refs["formRef"].resetFields();
      this.showVisiable = false;
    },

    save() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          // 发请求
          if (!this.editForm._id) {
            let result = await addRole(this.editForm);
            if (result.code == 200) {
              this.$message.success(result.msg);
              this.showVisiable = false;
              this.pageNo = 1;
              this.getRoleInfo(this.pageNo, this.pageSize);
            } else {
              this.$message.error(result.msg);
            }
          } else {
            let result = await updateRole(this.editForm);
            if (result.code == 200) {
              this.$message.success(result.msg);
              this.showVisiable = false;
              this.pageNo = 1;
              this.getRoleInfo(this.pageNo, this.pageSize);
            } else {
              this.$message.error(result.msg);
            }
          }
        }
      });
    },

    handleAdd() {
      this.editForm = {
        roleName: "",
        description: "",
        routes: [],
        power: [],
      };
      this.showVisiable = true;
      this.$nextTick(async function () {
        await this.$refs.tree.setCheckedKeys([]);
      });
    },

    handleEdit(row) {
      this.editForm = JSON.parse(JSON.stringify(row));
      this.showVisiable = true;
      this.$nextTick(async function () {
        await this.$refs.tree.setCheckedKeys(row?.power);
      });
      this.$refs.formRef.clearValidate();
    },

    async handleDelete(row) {
      let data = { _id: row._id };
      let result = await delRole(data);
      if (result.code == 200) {
        this.$message.success(result.msg);
        this.pageNo = 1;
        this.getRoleInfo(this.pageNo, this.pageSize);
      } else {
        this.$message.error(result.msg);
      }
    },

    async search() {
      let result = await searchRole(this.roleName);
      if (result.code == 200) {
        this.$message.success(result.msg);
        this.tableData = result.data;
      } else {
        this.$message.error(result.msg);
      }
    },

    reset() {
      this.roleName = "";
      this.pageNo = 1;
      this.getRoleInfo(this.pageNo, this.pageSize);
    },

    async getRoleInfo(pageNo, pageSize) {
      let result = await reqRoleList(pageNo, pageSize);
      if (result.code == 200) {
        this.tableData = result.data;
        this.total = result.total;
      } else {
        this.$message.error(result.msg);
      }
    },
    // 获取菜单列表
    async getMenuList() {
      let result = await reqMenuList();
      if (result.code == 200) {
        this.roleData = result.data;
      }
    },
    // 分页器
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getRoleInfo(this.pageNo, this.pageSize);
    },
    handleSizeChange(val) {
      this.pageNo = val;
      this.getRoleInfo(this.pageNo, this.pageSize);
    },
    // 角色列表勾选回调
    handleCheckChange() {
      this.editForm.power = this.$refs.tree.getCheckedKeys();
      this.editForm.routes = [];
      this.$refs.tree.getCheckedNodes(false, true).forEach((item) => {
        this.editForm.routes.push(item.name);
      });
    },
    // 头像上传
    handleAvatarSuccess(res, file) {
      this.editForm.avatar = res.url;
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
  },
  mounted() {
    this.getRoleInfo(this.pageNo, this.pageSize);
    this.getMenuList();
  },
};
</script>

<style lang="scss" scoped>
.main-container {
  .search {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  }

  .operation {
    margin-top: 5px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  }
  .table {
    margin-top: 5px;
    padding: 15px 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
</style>
<style lang="scss">
#editDialog {
  .avatar-uploader {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    display: block;
  }
}
</style>
